package com.twentyOne.ClothingLand.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.twentyOne.ClothingLand.dao.BaseDAO;
import com.twentyOne.ClothingLand.dao.IBarcodeDAO;
import com.twentyOne.ClothingLand.vo.Barcode;

public class BarcodeDAO extends BaseDAO implements IBarcodeDAO {

	@Override
	public int addBarcode(Barcode barcode) {
		
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.save(barcode);
		int ID = barcode.getId();
		tx.commit();
		session.close();
		return ID;
		
	}

	@Override
	public void modifyBarcode(Barcode barcode) {
		
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		String hql = "update Barcode set code=:code where id=:id";
		Query query = session.createQuery(hql);
		query.setString("code", barcode.getCode());
		query.setInteger("id", barcode.getId());
		query.executeUpdate();
		tx.commit();
		session.close();
		
	}

	@Override
	public Barcode searchBarcodeByCode(String code) {
		
		Session session = getSession();
		String hql = "from Barcode as b where b.code=" + code;
		Query query = session.createQuery(hql);
		List<Barcode> list = query.list();
		session.close();
		if (list.size() != 0) {
			Barcode barcode = list.get(0);
			return barcode;
		}else {
			return null;
		}
		
	}

	@Override
	public Barcode searchBarcodeByInfo(Barcode barcode) {
		
		Session session = getSession();
		String hql = "from Barcode as b where b.goodsId=" + barcode.getGoodsId() + " and " +"b.colorId=" + barcode.getColorId() 
						+ " and " + "b.sizeId=" + barcode.getSizeId() + " and " + "b.styleId=" + barcode.getStyleId();
		Query query = session.createQuery(hql);
		List<Barcode> list = query.list();
		session.close();
		if (list.size() == 0) {
			return null;
		}else {
			barcode = list.get(0);
			return barcode;
		}
		
	}

	@Override
	public List<Barcode> searchBarcodeByGoodsID(int goodsId) {

		Session session = getSession();
		String hql = "from Barcode as b where b.goodsId=" + goodsId;
		Query query = session.createQuery(hql);
		List<Barcode> list = query.list();
		session.close();
		if (list.size() == 0) {
			return null;
		}else {
			return list;
		}
		
	}

}
